package core

import (
	"github.com/gin-gonic/gin"
)

type Server struct {
	Engine *gin.Engine
}

func NewServer(release bool, templatesDir string) *Server {
	if release {
		gin.SetMode(gin.ReleaseMode)
	}

	s := &Server{
		Engine: gin.New(),
	}

	// 加载模板目录
	if templatesDir != "" {
		s.Engine.LoadHTMLGlob(templatesDir)
	}

	return s
}

// 注册路由
func (s *Server) registerRouters(rg *gin.RouterGroup, controllers ...ControllerInterface) {
	for _, v := range controllers {
		v.Register(rg)
	}
}

// 直接注册
func (s *Server) Router(controllers ...ControllerInterface) *Server {
	s.registerRouters(s.Engine.Group("/"), controllers...)
	return s
}

// 整体分组注册
func (s *Server) RouterGroup(group string, controllers ...ControllerInterface) *Server {
	rg := s.Engine.Group(group)
	s.registerRouters(rg, controllers...)

	return s
}

// 运行服务
func (s *Server) Run(addr string) {
	s.Engine.Run(addr)
}
